import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
//import { validateLink } from '../../../helpers/dataValidation';

import {
  authorizedRouteHandler,
  ControllerMethodTypes,
  defaultRouteHandler,
} from '../../../../interfaces';
import { Request } from 'hyper-express';
import { showSelectedObjectKeys } from '../../../helpers/utilsJS';
import { attachments } from '../../../../../prisma/generated/uctoo';
import { setExCache } from '../../../helpers/redis';
import moment from 'moment';
import fs from 'fs';
import path from 'path';
  //#region AutoCreateCode
import {
  createAttachments,
  deleteAttachmentsFromDatabase,
  deleteMultiAttachmentsFromDatabase,
  editAttachmentsInDatabase,
  editMultiAttachmentsInDatabase,
  getAttachmentsFromDatabase,
  getAttachmentssFromDatabase,
  queryAttachmentssFromDatabase,
  countAttachmentss
} from '../../../services/uctoo/attachments';

class uctooAttachmentsController {

  protected validateAndDestructureBody = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    const body = await req.json();
    const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
    const uctooAttachments = showSelectedObjectKeys(body, keysArray) as attachments;
    uctooAttachments.creator = userId;

    return uctooAttachments;
  };
  public add: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const uctooAttachments = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      if (!uctooAttachments) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

      const createdAttachments = await createAttachments(uctooAttachments);
      if (!createdAttachments) return res.status(500).json({ errno: "50001", errmsg: "database query failed" });

      res.status(200).json(createdAttachments);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public edit: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const body = await req.json();
      const { id,ids,force } = body;

      if(ids){
        const uctooAttachments = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooAttachments) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedAttachments = await editMultiAttachmentsInDatabase(uctooAttachments, JSON.parse(ids), user);
        
        if (typeof editedAttachments === 'object' && 'success' in editedAttachments) {
          if (!editedAttachments.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: editedAttachments.reason,
              ...(editedAttachments.attachmentsId && { attachmentsId: editedAttachments.attachmentsId })
            });
          }
          return res.status(200).json(editedAttachments.data);
        }
        
        res.status(200).json(editedAttachments);
      }else{
        const uctooAttachments = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooAttachments) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedAttachments = await editAttachmentsInDatabase(uctooAttachments, uctooAttachments.id, user);
        
        if (typeof editedAttachments === 'object' && 'success' in editedAttachments) {
          if (!editedAttachments.success) {
            return res.status(403).json({ errno: "40301", errmsg: editedAttachments.reason });
          }
          return res.status(200).json(editedAttachments.data);
        }
        res.status(200).json(editedAttachments);
      }      
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public delete: authorizedRouteHandler = async (req, res) => {
    try {
      const body = await req.json();
      const { id,ids,force } = body;
      const user = res.locals.id.user;

      if(ids){
        const deletionResult = await deleteMultiAttachmentsFromDatabase(JSON.parse(ids), force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: deletionResult.reason,
              ...(deletionResult.attachmentsId && { attachmentsId: deletionResult.attachmentsId })
            });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }else{
        const deletionResult = await deleteAttachmentsFromDatabase(id, force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({ errno: "40301", errmsg: deletionResult.reason });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }

      res.status(200).json({ desc: '删除成功' });
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getSingle: authorizedRouteHandler = async (req, res) => {
    try {
      const { id } = req.params;
      const user = res.locals.id.user;

      const attachmentsFromDb = await getAttachmentsFromDatabase(id, user);
      if (!attachmentsFromDb) {
        return res.status(404).json({ 
          errno: "40401", 
          errmsg: '未找到该实体或您没有权限访问' 
        });
      }

      res.status(200).json(attachmentsFromDb);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getMany: authorizedRouteHandler = async (req, res) => {
    try {
      const limit = parseInt(req.params.limit);
      const page = parseInt(req.params.page) || 0;
      const skip = parseInt(req.params.skip) || 0;
      const query = req.query;
      
      if (limit > 100) return res.status(400).json({ errno: "40002", errmsg: '请求数量不能超过100条' });
      if (isNaN(limit)) return res.status(400).json({ errno: "40003", errmsg: '请求数量必须是数字' });
      
      const user = res.locals.id.user;
      const totalCount = await countAttachmentss(user);
      
      if (query) {
        const attachmentssFromDb = await queryAttachmentssFromDatabase(limit, page, skip, query, user);
        if (!attachmentssFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount: totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          attachmentss: attachmentssFromDb
        });
      } else {
        const attachmentssFromDb = await getAttachmentssFromDatabase(limit, skip, page, user);
        if (!attachmentssFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount:totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          attachmentss: attachmentssFromDb
        });
      }


    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  //#endregion AutoCreateCode

  public fileUpload: authorizedRouteHandler = async (req, res) => {
    const id = res.locals.id;
    console.log('id:', id)
    const account_id = id.user;  //已登录用户的id即user表id字段
    if (account_id === undefined) return res.status(403).send('You must be logged in to use this endpoint.');
    let savePath;
    let fileUrl;
    let apiUrl = process.env.API_URL;
    try {
      await req.multipart(async (field) => {
        console.log(field.file)
        if (field.file) {
          const rootDir = path.resolve('assets')
          const dayStr = moment().format("YYYYMMDD")
          const fileName = field.file.name;
          let dirPath = `${rootDir}/${dayStr}`;
          savePath = `${dirPath}/${fileName}`;
          fileUrl = `${apiUrl}/assets/${dayStr}/${fileName}`;
          if (!fs.existsSync(dirPath)) {
            console.log('dir not exist');
            fs.mkdirSync(dirPath, { recursive: true });
          }
          //console.log('dirPath:', dirPath);
          //console.log('savePath:', savePath);
          await field.write(savePath);
          if (savePath) {
            const stats = fs.statSync(savePath);
            // 这里将数据插入到db
            const uctooAttachments = {
              path: `${dayStr}/${fileName}`,
              url: fileUrl,
              mime_type: field.mime_type,
              file_ext: path.extname(savePath),
              filesize: stats.size,
              filename: field.file.name,
              driver: "local",
              creator: account_id //"505cf909-5e0e-4dde-b215-74274d2cc548"
            };
            await createAttachments(uctooAttachments)
          }
        }
      });
    } catch (error) {
      console.error(error);
      if (typeof error as string === 'FILES_LIMIT_REACHED') {
        return res.status(403).send('You sent too many files! Try again.');
      } else {
        return res.status(500).send('Oops! An uncaught error occur on our end.');
      }
    }
    if (savePath) {
      return res.json({ url: fileUrl });
    } else {
      return res.status(400).send('No file was received. Please try again.');
    };
  };
}

export default uctooAttachmentsController;
